// src/components/Recorder.jsx
import { useState } from 'react';
import axios from 'axios';
import PropTypes from 'prop-types';
import { useReactMediaRecorder } from 'react-media-recorder';
import { Button } from 'antd';

const Recorder = ({ onTranscriptionComplete }) => {
  const [recordingStatus, setRecordingStatus] = useState('inactive');
  const [audioBlob, setAudioBlob] = useState(null);

  const { status, startRecording, stopRecording, mediaBlobUrl } = useReactMediaRecorder({
    video: false,
    audio: true,
    onStop: (blobUrl, blob) => {
      setAudioBlob(blob);
      setRecordingStatus('stopped');
    },
  });

  const sendAudioToBackend = async () => {
    if (audioBlob) {
      const formData = new FormData();
      formData.append('file', new Blob([audioBlob], { type: 'audio/wav' }), 'recording.wav');
  
      try {
        const response = await axios.post('http://localhost:8080/transcribe', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        console.log('Response from backend:', response.data); // 调试信息
        onTranscriptionComplete(response.data); // 传递整个响应对象
      } catch (error) {
        console.error('Error uploading file:', error);
      }
    }
  };

  return (
    <div>
      <Button onClick={startRecording} disabled={status === 'recording'}>
          Start Recording
      </Button>
      <Button onClick={stopRecording} disabled={status !== 'recording'}>
        Stop Recording
      </Button>
      <Button onClick={sendAudioToBackend} disabled={!audioBlob || recordingStatus !== 'stopped'}>
        Send to Backend
      </Button>
      {mediaBlobUrl && <audio controls src={mediaBlobUrl} />}
    </div>
  );
};

// 添加 propTypes 验证
Recorder.propTypes = {
    onTranscriptionComplete: PropTypes.func.isRequired,
  };
  

export default Recorder;